#!/bin/bash

#获取路径
export SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

store_Dir="$SCRIPT_DIR/Store"
Conf_Dir="$SCRIPT_DIR/conf"
Log_Dir="$SCRIPT_DIR/logs"
Daili="$SCRIPT_DIR/Daili"
chmod +x $SCRIPT_DIR/scripts/*

#clash版本号
edition='2.0.24'


## 获取CPU架构信息
source $SCRIPT_DIR/scripts/get_cpu_arch.sh

if [[ -z "$CpuArch" ]]; then
	echo "无法获取CPU体系结构"
	exit 1
fi



#################### 下载clash ####################

main_program="clash-linux-amd64"
if [ ! -e "$Daili/$main_program" ]; then
  echo -e "没找到主程序，开始下载"

  case $CpuArch in
    "x86_64" | "amd64")
      archive_url="https://gitee.com/LiYunYueHai/proxy/releases/download/1.0/clash_${edition}_linux_amd64.tar.gz"
      Architecture="amd64"
      ;;
    "aarch64" | "arm64")
      archive_url="https://gitee.com/LiYunYueHai/proxy/releases/download/1.0/clash_${edition}_linux_arm64.tar.gz"
      Architecture="arm64"
      ;;
    "armv7")
      echo -e "\033[31m\n[ERROR] 暂无该架构的主程序！\033[0m"
      exit 1
      ;;
    *)
      echo -e "\033[31m\n[ERROR] Unsupported CPU Architecture！\033[0m"
      exit 1
      ;;
  esac

  wget "$archive_url" -P "$Daili" && cd "$Daili"

  tar -zxvf "clash_${edition}_linux_${Architecture}.tar.gz" || { echo "解压文件出错"; exit 1; }

  mv "clash" "$main_program"
  rm -rf "clash_${edition}_linux_${Architecture}.tar.gz"
  rm -rf LICENSE
  rm -rf README.md
else
  echo -e "存在，跳过下载"
fi

# 给执行权限
chmod +x $SCRIPT_DIR/Daili/*

#################### 函数定义 ####################

# 自定义action函数，实现通用action功能
success() {
	echo -en "\\033[60G[\\033[1;32m  OK  \\033[0;39m]\r"
	return 0
}

failure() {
	local rc=$?
	echo -en "\\033[60G[\\033[1;31mFAILED\\033[0;39m]\r"
	[ -x /bin/plymouth ] && /bin/plymouth --details
	return $rc
}

action() {
	local STRING rc

	STRING=$1
	echo -n "$STRING "
	shift
	"$@" && success $"$STRING" || failure $"$STRING"
	rc=$?
	echo
	return $rc
}

# 判断命令是否正常执行 函数
if_success() {
	local ReturnStatus=$3
	if [ $ReturnStatus -eq 0 ]; then
		action "$1" /bin/true
	else
		action "$2" /bin/false
		exit 1
	fi
}

#################### 任务执行 ####################



read -p "请输入代理链接：" URL

echo -e '\n正在检测订阅地址...'
Text1="Clash订阅地址可访问！"
Text2="Clash订阅地址不可访问！"
#curl -o /dev/null -s -m 10 --connect-timeout 10 -w %{http_code} $URL | grep '[23][0-9][0-9]' &>/dev/null
curl -o /dev/null -L -k -sS --retry 5 -m 10 --connect-timeout 10 -w "%{http_code}" $URL | grep -E '^[23][0-9]{2}$' &>/dev/null
ReturnStatus=$?
if_success $Text1 $Text2 $ReturnStatus

# 拉取更新config.yml文件
echo -e '\n正在下载Clash配置文件...'
Text3="配置文件config.yaml下载成功！"
Text4="配置文件config.yaml下载失败，退出启动！"

# 尝试使用curl进行下载
curl -L -k -sS --retry 5 -m 10 -o $store_Dir/clash.yaml $URL
ReturnStatus=$?
if [ $ReturnStatus -ne 0 ]; then
	# 如果使用curl下载失败，尝试使用wget进行下载
	for i in {1..10}
	do
		wget -q --no-check-certificate -O $store_Dir/clash.yaml $URL
		ReturnStatus=$?
		if [ $ReturnStatus -eq 0 ]; then
			break
		else
			continue
		fi
	done
fi
if_success $Text3 $Text4 $ReturnStatus

\cp -a $store_Dir/clash.yaml $store_Dir/clash_config.yaml

## 判断订阅内容是否符合clash配置文件标准，尝试转换（当前不支持对 x86_64 以外的CPU架构服务器进行clash配置文件检测和转换，此功能将在后续添加）
if [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
	echo -e '\n判断订阅内容是否符合clash配置文件标准:'
	bash $SCRIPT_DIR/scripts/clash_profile_conversion.sh
	sleep 3
fi

## Clash 配置文件重新格式化及配置
# 取出代理相关配置 
#sed -n '/^proxies:/,$p' $store_Dir/clash.yaml > $store_Dir/proxy.txt
sed -n '/^proxies:/,$p' $store_Dir/clash_config.yaml > $store_Dir/proxy.txt

# 合并形成新的config.yaml
cat $store_Dir/templete_config.yaml > $store_Dir/config.yaml
cat $store_Dir/proxy.txt >> $store_Dir/config.yaml
\cp $store_Dir/config.yaml $Conf_Dir/

# Configure Clash Dashboard
cd && cd proxy
Work_Dir=$(cd $(dirname $0); pwd)
Dashboard_Dir="${Work_Dir}/browser"
sed -ri "s@^# external-ui:.*@external-ui: ${Dashboard_Dir}@g" $Conf_Dir/config.yaml
#sed -r -i '/^secret: /s@(secret: ).*@\1'${Secret}'@g' $Conf_Dir/config.yaml


echo -e '\n正在启动Clash服务...'
Text5="服务启动成功！"
Text6="服务启动失败！"
if [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
	nohup $SCRIPT_DIR/Daili/clash-linux-amd64 -d $Conf_Dir &> $Log_Dir/clash.log &
	ReturnStatus=$?
	if_success $Text5 $Text6 $ReturnStatus
elif [[ $CpuArch =~ "aarch64" ||  $CpuArch =~ "arm64" ]]; then
	nohup $SCRIPT_DIR/Daili/clash-linux-arm64 -d $Conf_Dir &> $Log_Dir/clash.log &
	ReturnStatus=$?
	if_success $Text5 $Text6 $ReturnStatus
elif [[ $CpuArch =~ "armv7" ]]; then
	nohup $SCRIPT_DIR/Daili/clash-linux-armv7 -d $Conf_Dir &> $Log_Dir/clash.log &
	ReturnStatus=$?
	if_success $Text5 $Text6 $ReturnStatus
else
	echo -e "\033[31m\n[ERROR] Unsupported CPU Architecture！\033[0m"
	exit 1
fi

cat>/etc/profile.d/clash.sh<<EOF
# 开启系统代理
function proxy_on() {
	export http_proxy=http://127.0.0.1:7890
	export https_proxy=http://127.0.0.1:7890
	export no_proxy=127.0.0.1,localhost
    	export HTTP_PROXY=http://127.0.0.1:7890
    	export HTTPS_PROXY=http://127.0.0.1:7890
 	export NO_PROXY=127.0.0.1,localhost
	echo -e "\033[32m[√] 已开启代理\033[0m"
}

# 关闭系统代理
function proxy_off(){
	unset http_proxy
	unset https_proxy
	unset no_proxy
  	unset HTTP_PROXY
	unset HTTPS_PROXY
	unset NO_PROXY
	echo -e "\033[31m[×] 已关闭代理\033[0m"
}
EOF

echo -e "请输入\nnetstat -tln | grep -E '9090|789.'\n查看是否有端口\n\n远程登录请使用http://<ip>:9090/ui\n\n密码：b&ZlKTte5OnEt2Sn\n\n"
echo -e "请执行以下命令加载环境变量: source /etc/profile.d/clash.sh\n"
echo -e "请执行以下命令开启系统代理: proxy_on\n"
echo -e "若要临时关闭系统代理，请执行: proxy_off\n"